<?php
require('../includes/init.php');
require('../includes/lib_order.php');
$domain = "https://www.pentalink.com";
$sql = "SELECT count(*) FROM `cart` WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
$cart_sum = $db->getOne($sql);
?>
<?php include('./header.php');?>
<link href="../css/v1/shopcart.css" rel="stylesheet" type="text/css" />
<style>
    .pcsnum {
        font-size: 12px;
    }
    .increase {
        line-height: 12px;
    }
    .reduce{
        line-height: 12px;
    }
    .ksbj_cont a{
        color: white;
    }
    .cut_cont a{
        color: #E90211;
    }
    .foot_content_box{
        z-index: 1000!important;
    }
</style>
            <!-- 头部搜索框以及导航栏 -->
            <div class="header_div">
                <?php include('./common/search.php');?>
                <?php include('./common/nav.php');?>
            </div>
            
            <!-- 标签 -->
            <div class="post_position">
                <span class="home_span"><a href="./index.php">首页 > </a></span>
                <span><a>购物车列表</a></span>
            </div>

            <!-- 我的购物车 -->     
            <div class="shop_car_content box">
                <h1 class="box shop_car_h1">我的购物车（<span class="cart_sum"><?php echo $cart_sum; ?></span>）</h1>
                <table class="table table-condensed">
                    <thead>
                        <tr>
                            <th>商品品类</th>
                            <th style="text-align: center;">商品状态</th>
                            <th style="text-align: center;">单价</th>
                            <th style="text-align: center;">数量</th>
                            <th style="text-align: center;">当前剩余库存(个)</th>
                            <th style="text-align: center;">折扣</th>
                            <th style="text-align: center;">小计</th>
                            <th style="text-align: center;">操作</th>
                        </tr>
                    </thead>
                    <tbody>

                        <?php
                        $tj_cate = array();//下面的推荐分类关联
                        $cart_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id'], 1);
                        $total = order_fee($cart_list);
                        $total_num = 0;//总的数量
                        if(!empty($cart_list)):
                        foreach($cart_list as $key => $cart):
                            $sql = "SELECT * FROM `product` WHERE `product_id`='".$cart['product_id']."';";
                            $product = $db->getRow($sql);
                            //图片
                            //$sql = "SELECT * FROM `product_pic` WHERE `product_id`='".$product['product_id']."' LIMIT 1;";
                            $sql = "SELECT *,if(`sort_order` > '0',1,0) AS `is_order` FROM `product_pic` WHERE `ftype`=1 AND `product_id`='".$product['product_id']."' ORDER BY `is_order` DESC, `sort_order` LIMIT 1;";
                            //echo $sql;
                            $pic = $db->getRow($sql);
                            //规格信息
                            $sql = "SELECT * FROM `product_detail` WHERE `pd_id`='".$cart['pd_id']."';";
                            $gg = $db->getRow($sql);
                            
                            $decimals = $product['bigcate_id']=='1'?4:2;
                            
                            $tj_cate[] = $product['cate_id'];
                        ?>

                            <tr class="pid_<?php echo $cart['pd_id'];?>"  pid="<?php echo $cart['pd_id'];?>">
                                <td>
                                    <div class="td_checkbox"><input autocomplete="off" onclick="CheckSelect();" pid="<?php echo $cart['pd_id'];?>" cart_id="<?php echo $cart['cart_id'];?>"  class="item_checkbox <?php if($cart['price'] > 0): ?> item_effect_checkbox <?php endif; ?>" type="checkbox" 
                                    <?php if($cart['price'] == 0): ?> disabled="disabled" <?php endif; ?>
                                    <?php if($cart['price'] > 0): ?> checked <?php endif; ?>

                                    /></div>
                                    <?php
                                    $cate_arr = explode(',', $product['cate_ids']);
                                    $cateId = $cate_arr[0];
                                    ?>
                                    <a href="./proDetail.php?id=<?php echo $product['product_id'];?>&cate_id=<?php echo $cateId;?>">
                                        <div class="td_img"><img src="<?php echo $domain; ?>/upload<?php echo $pic['pic100'];?>" alt="<?php echo $product['title'];?>"></div>
                                    </a>
                                    <a href="./proDetail.php?id=<?php echo $product['product_id'];?>&cate_id=<?php echo $cateId;?>">
                                        <div class="td_p">
                                            <p class="p1"><?php echo $product['title'];?></p>
                                            <p class="p1" style="font-size: 12px;">
                                                <?php echo $gg['sku'];//yjt_sku($gg['pd_id']);?><br />
                                                规格：<?php echo $gg['xy_value'];?><br />
                                                包装：<?php echo $gg['pkg'];?>个/包<br />
                                                <?php if($gg['brand_id']){?>品牌：<?php echo $cfg_brand[$gg['brand_id']];?><?php }?>
                                                <?php if($gg['is_stocklast']=='1'):?>
                                                <br />库存：<?php echo $gg['stock'];?>
                                                <br /><span class="all-kinds-mark clearance-end">售完即止</span>
                                                <?php endif;?>
                                                </div>
                                                <?php if($gg['is_stocklast']=='1'):?>
                                                <b class="goods-mark goods-mark-clearance goods-mark-imglist">清仓</b>
                                                <?php endif;?>
                                            </p>
                                        </div>
                                    </a>
                                </td>
                                <td style="text-align: center;color: #666666;">
                                    <?php if($cart['price'] == 0): ?>
                                    不可购买
                                    <div style="width: 100%;height: 5px;"></div>
                                    <a target="_blank" href="https://p.qiao.baidu.com/cps4/chatIndex?siteToken=fa9edd6c146a2526c2a20e5302b32e57&speedLogId=160263314181962f2_1602633141819_29294&reqParam=%7B%22from%22%3A0,%22sessionid%22%3A%22%22,%22siteId%22%3A%221050923%22,%22tid%22%3A%22-1%22,%22userId%22%3A%223244648%22,%22ttype%22%3A1,%22siteConfig%22%3A%7B%22eid%22%3A%223244648%22,%22queuing%22%3A%22%22,%22siteToken%22%3A%22fa9edd6c146a2526c2a20e5302b32e57%22,%22userId%22%3A%223244648%22,%22isGray%22%3A%22false%22,%22wsUrl%22%3A%22wss%3A%2F%2Fp.qiao.baidu.com%2Fcps4%2Fwebsocket%22,%22likeVersion%22%3A%22generic%22,%22siteId%22%3A%221050923%22,%22online%22%3A%22true%22,%22webRoot%22%3A%22%2F%2Fp.qiao.baidu.com%2Fcps4%2F%22,%22bid%22%3A%22158519076548463203%22,%22isSmallFlow%22%3A0,%22isPreonline%22%3A0,%22invited%22%3A0%7D,%22config%22%3A%7B%22themeColor%22%3A%224d74fa%22%7D%7D" style="color: #666666;">咨询客服</a>
                                    <?php endif;?>
                                    <?php if($cart['price'] > 0): ?>
                                    可以购买
                                    <?php endif;?>
                                </td>
                                <td style="text-align: center;" id="lp_<?php echo $gg['pd_id'];?>"><?php echo price_format($cart['price'], true, $decimals);?></td>
                                <td style="text-align: center;">
                                    <a href="javascript:void(0);" class="reduce" onclick="ShopcartUpdateNumber(<?php echo $gg['pd_id'];?>,-1);">-</a>
                                    <input type="text" id="lq_<?php echo $gg['pd_id'];?>" class="pcsnum" pkg="<?php echo $gg['pkg'];?>" value="<?php echo $cart['pcount'];?>" cvalue="<?php echo $cart['pcount'];?>" stock="<?php echo $gg['stock'];?>" onchange="ShopcartUpdateNumber(<?php echo $gg['pd_id'];?>,0);" />
                                    <a href="javascript:void(0);" class="increase" onclick="ShopcartUpdateNumber(<?php echo $gg['pd_id'];?>,1);">+</a>          
                                </td>
                                <td style="text-align: center;" id="ls_<?php echo $gg['pd_id'];?>"><?php if($gg['stock'] >= $cart['pcount']) echo "现货"; else echo "部分现货";?></td>
                                <td style="text-align: center;" class="zhek">￥0</td>
                                <td style="text-align: center;"  class="e9 bold">￥<span id="lt_<?php echo $gg['pd_id'];?>"><?php echo $cart['price']*$cart['pcount'];?></span></td> 
                                <td style="text-align: center;" class="remove" onclick="ShopcartDeleteCurrent(<?php echo $gg['pd_id'];?>);">删除</td>
                            </tr>
                        <?php
                        $total_num += $cart['pcount'];
                        endforeach;
                        endif;
                        ?>
                    </tbody>
                </table>

                <div class="shop_car_all box">
                    <input id="scckb" onclick="ShopcartSelect();" checked  class="allchek_input" type="checkbox" autocomplete="off">
                    <span style="cursor: pointer;" onclick="ShopcartSelectAll();">全选</span>
                    <span style="cursor: pointer;" onclick="ShopcartDeleteSelected();">删除所选</span>
                    <span></span>
                </div>
                
                <div class="order_price_detail box" style="margin-top:0">
                    <ul>
                        <li><p>折扣：<span class="e9">-￥<span class="zhekou"><?php echo $total['discount'];?></span></span></p></li>
                        <li><p>运费：<span  class="e9">+￥<span class="yunfei"><?php echo $total['goods_price'] == 0 ? 0 : $total['shipping_fee'];?></span></span></p></li>
                        <li><p>商品总计：<span  class="e9">￥<span class="good_price"><?php echo $total['goods_price'];?></span></span></p></li>
                    </ul>
                </div>

                <div class="order_commit box">
                    <p>订单总计：<span class="e9">￥<span class="all_price"><?php echo $total['goods_price'] == 0 ? 0 : $total['total_fee'];?></span></span></p>
                    <a onclick="goPay()" class="commit_btn">去结算</a>
                </div>

            </div>
<?php include('./footer.php');?>
<script type="text/javascript" src="/js/artDialog4.1.7/artDialog.js?skin=blue"></script> 
<script>
    //全选
    function ShopcartSelect() {
        var ckb = $("#scckb").attr("checked");
        if (ckb == "checked") {
            $(".item_effect_checkbox").attr("checked", true);
        }
        else {
            $(".item_effect_checkbox").attr("checked", false);
        }

        var cartIds = ""
        $(".item_effect_checkbox").each(function() {
            if ($(this).attr("checked") != "checked") {
                hasNoCheck = true
            }else{
                cartIds += $(this).attr("cart_id") + ","
            }
        });
        UpdateCheckBox(cartIds)
    }
    function ShopcartSelectAll() {
        var ckb = $("#scckb").attr("checked");
        if (ckb == "checked") {
            $("#scckb").attr("checked", false);
        }
        else {
            $("#scckb").attr("checked", true);
        }
        ShopcartSelect();
    }
    function CheckSelect(){
        var hasNoCheck = false
        var cartIds = ""
        $(".item_effect_checkbox").each(function() {
            if ($(this).attr("checked") != "checked") {
                hasNoCheck = true
            }else{
                cartIds += $(this).attr("cart_id") + ","
            }
        });
        if (hasNoCheck == true){
            $("#scckb").attr("checked", false);
        }else{
            $("#scckb").attr("checked", true);
        }
        UpdateCheckBox(cartIds)
    }

    function UpdateCheckBox(ids){
        $.post("/ajax/cart.php", { "act": "ShopcartUpdateCheckbox", "ids": ids }, function(data) {
                if(data.goods_price == 0){
                    data.shipping_fee = 0
                    data.total_fee = 0
                    data.discount = 0
                }

                $(".good_price").text(data.goods_price);//商品总金额
                $(".zhekou").text(data.discount);//折扣
                
                $(".yunfei").text(data.shipping_fee);//运费
                $(".all_price").text(data.total_fee);//总金额
        });
    }

    //删除选中的
function ShopcartDeleteSelected()
{
    var cfn = confirm("您确定要删除所选记录吗?");
    if (!cfn) {
        return false;
    }
    var pids = "";
    $(".item_effect_checkbox").each(function() {
        var ck = $(this).attr("checked");
        if ($(this).attr("checked") == "checked") {
			pids += pids=="" ? $(this).attr("pid") : ","+$(this).attr("pid");
        }
    });
	
    if (pids == "") {
		art.dialog({
			content: '请勾选需要删除的记录!',
			time: 3,
			title: '系统提示（3秒后自动关闭）',
			icon: 'warning',
			ok: true,
			lock: true,
            fixed: true,
            top: "200px",
		});
        return false;
    }

    $.post("/ajax/cart.php", { "act": "ShopcartDeleteSelected", "pids": pids }, function(data) {
		if(data.type == '1')
		{
			//删除页面上的元素
			var ps = pids.split(",");
			for (var i = 0; i < ps.length; i++) {
                $(".pid_" + ps[i]).remove();
			}
			//更新单据金额
			$(".cart_sum").text(data.pnum);//总数量
			$(".good_price").text(data.pta);//商品总金额
			$(".zhekou").text(data.pda);//折扣
			
            
            $(".yunfei").text(data.scpf);//运费
            $(".all_price").text(data.scpot);//总金额

			return true;
		}
		else if(data.type == '2')
		{
			//刷新页面显示购物车为空。
			window.location = './cart.php';
		}
		else
		{
			return false;
		}
	});
}

//删除
function ShopcartDeleteCurrent(pid) {
    var cfn = confirm("您确定要删除当前商品吗?");
    if (!cfn) {
        return false;
    }
    $.post("/ajax/cart.php", { "act":'DelCurrent', "pid": pid }, function(data, state) {
		if(data.type == '1')
		{
			//删除页面上的元素
            $(".pid_" + pid).remove();

			//更新单据金额
			$(".cart_sum").text(data.pnum);//总数量
			$(".good_price").text(data.pta);//商品总金额
			$(".zhekou").text(data.pda);//折扣
            
            $(".yunfei").text(data.scpf);//运费
            $(".all_price").text(data.scpot);//总金额

			return true;
		}
		else if(data.type == '2')
		{
			//刷新页面显示购物车为空。
			window.location = './cart.php';
		}
		else
		{
			return false;
		}
	});
}

//更新购物车产品数量
function ShopcartUpdateNumber(pid, ptype) {
    var lp = "#lp_" + pid;//商品单价
    var lq = "#lq_" + pid;//商品购买数量
    var ls = "#ls_" + pid;//库存
    var lt = "#lt_" + pid;//小计
    var txt = document.getElementById("lq_" + pid);

    var pkg = $(lq).attr("pkg");
    var value = $(lq).attr("value");
    var cvalue = $(lq).attr("cvalue");//原来的值
    var stock = $(lq).attr("stock");

    var regexp = /^[0-9]{1,10}$/;  //验证数字
    if (!value.match(regexp)) {
        alert("数量输入错误！");
        txt.focus();
        return false;
    }
    if (value % pkg != 0) {
        alert("请按包装量的倍数购买！");		
        txt.focus();
        return false;
    }

    pkg = parseInt(pkg, 10);
    value = parseInt(value, 10);
    cvalue = parseInt(cvalue, 10);
    stock = parseInt(stock, 10);
    
    if (ptype == 0) {//update
        if (value == cvalue) return false;//nochange return
    }
    switch (ptype) {
        case -1: //-
            value = value - pkg;
            break;
        case 0: //update
            
            break;
        case 1: //+
            value = value + pkg;
            break;
    }

    if (value < 0) value = 0;
    if (value == 0) {
        alert('数量不能为0，需要删除该产品，请点击删除！');
		return false;
    }
    var ids = ""
    $(".item_effect_checkbox").each(function() {
        if ($(this).attr("checked") != "checked") {
            hasNoCheck = true
        }else{
            ids += $(this).attr("cart_id") + ","
        }
    });

    $.post("/ajax/cart.php", { "act": "ShopcartUpdateNumber", "pid": pid, "pcount": value, "stock": stock, ids: ids}, function(data) {
		if(data.type == '1')
		{
			$(lp).text("￥" + data.price);//单品价格
            $(lt).text(data.ltotal);//单品价格合计
            //$(lq).val(value);//数量
			$(lq).val(data.pcount);//数量采用回调的数量，防止清仓的超过库存量
            $(lq).attr("cvalue", value); //备份数量
            $(ls).text(data.lstock); //库存情况

			$(".good_price").text(data.goods_price);//商品总金额
			$(".zhekou").text(data.discount);//折扣
            
            $(".yunfei").text(data.shipping_fee);//运费
            $(".all_price").text(data.total_fee);//总金额


            if(data.goods_price == 0){
                $(".yunfei").text(0);//运费
                $(".all_price").text(0);//总金额
            }
		}
		else
		{
			alert(data.msg);
			return false;
		}
	});
}
function goPay(){
    var productPrice = "<?php echo $total['goods_price'];?>"
    if (productPrice == 0){
        alert("没有可结算的商品")
        return
    }
    //唤起登陆框
    <?php if($_SESSION[SESSION_PREFIX]['user_id']=='' || $_SESSION[SESSION_PREFIX]['user_id']=='0'):?>
    $(".login_alert_block").show();
    return;
    <?php endif;?>

    var cartIds = ""
    $(".item_effect_checkbox").each(function() {
        if ($(this).attr("checked") != "checked") {
            hasNoCheck = true
        }else{
            cartIds += $(this).attr("cart_id") + ","
        }
    });
    if (cartIds == ""){
        alert("请选择要支付的商品")
        return
    }

        
    location.href="./confirm.php?ids=" + cartIds
}
</script>